#!/bin/bash

# Define a help function to print the usage and parameter description of the script
help() {
  echo "Usage: $0 DISK MOUNT_POINT"
  echo "This script partitions and formats a specified disk as xfs, then mounts it to a specified directory, and finally writes the mount entry to /etc/fstab."
  echo "Parameters:"
  echo "  DISK: The disk to be partitioned, such as /dev/sdb"
  echo "  MOUNT_POINT: The directory to mount the partition, such as /data"
}

# Specify the disk to be partitioned, such as /dev/sdb
DISK=$1

# Specify the directory to mount the partition, such as /data
MOUNT_POINT=$2

# Check the number of parameters, if less than two, call the help function and exit
if [ $# -lt 2 ]; then
  help
  exit 1
fi

# Use the fdisk command to create a primary partition, using the default size
echo -e "n\np\n1\n\n\nw" | fdisk $DISK

# Get the device name of the partition, such as /dev/sdb1
PARTITION=$(fdisk -l $DISK | grep -Eo "$DISK[0-9]+")

# Use the mkfs.xfs command to format the partition as xfs
mkfs.xfs -f $PARTITION

# Create the mount directory, if it does not exist
mkdir -p $MOUNT_POINT

# Use the mount command to mount the partition to the specified directory
mount -t xfs $PARTITION $MOUNT_POINT

# Get the UUID of the partition, for writing to /etc/fstab
UUID=$(blkid $PARTITION -s UUID | grep -o "UUID=\"[^\"]*\"" | cut -d '"' -f 2)

# Write the mount entry to /etc/fstab, using UUID and default options
echo "UUID=$UUID $MOUNT_POINT xfs defaults 0 0" >> /etc/fstab

